import { createAction, actionTypeCreatorWithNameSpace } from './util';
import agent from 'agent';

const actionTypeCreator = actionTypeCreatorWithNameSpace('user');

export const login = createAction(actionTypeCreator('login'), (loginInfo) => {
  return agent.post('/api/users/login')
    .type('form')
    .send(loginInfo)
    .then(response => response.body);
});

export const logout = createAction(actionTypeCreator('logout'), () => {
  return agent.post('/api/users/logout')
    .then(true);
});

export const nativeLogout = createAction(actionTypeCreator('nativeLogout'));

export const getLogined = createAction(actionTypeCreator('getLogined'), () => {
  return agent.get('/api/users/current')
    .then(response => response.body);
});

export const search = createAction(actionTypeCreator('search'), (query) => {
  return agent.get('/api/users/search')
    .query(query)
    .then(response => response.body);
});

export const create = createAction(actionTypeCreator('userById'), (user) => {
  return agent.post('/api/users')
    .type('form')
    .send(user);
});

export const resetPassword = createAction(actionTypeCreator('userById'), (userId, password) => {
  return agent.post(`/api/users/${userId}/resetPassword`)
    .type('form')
    .send({ password: password });
});

export const changePassword = createAction(actionTypeCreator('userById'), (password) => {
  return agent.post('/api/users/current/changePassword')
    .type('form')
    .send(password);
});

export const updateProfile = createAction(actionTypeCreator('userById'), (userProfile) => {
  return agent.post('/api/users/current/profile')
    .type('form')
    .send(userProfile);
});

export const lockUser = createAction(actionTypeCreator('userById'), (userId) => {
  return agent.post(`/api/users/${userId}/lock`);
});

export const unlockUser = createAction(actionTypeCreator('userById'), (userId) => {
  return agent.post(`/api/users/${userId}/unlock`);
});

export const suggest = createAction(actionTypeCreator('suggest'), (key) => {
  return agent.get('/api/users/suggest')
    .query({ key })
    .then(response => response.body);
});

export const getUserInfo = createAction(actionTypeCreator('userById'), (userId) => {
  return agent.get(`/api/users/${userId}`)
    .then(response => response.body);
});
